package com.atguigui.leetcode;

/**
 * P面试题 01.05OneAwayLcci
 * <p>
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/5/13 8:48
 */
public class OneAwayLcci {
    public static void main(String[] args) {
        Solution solution = new OneAwayLcci().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public boolean oneEditAway(String first, String second) {

            int m = first.length(), n = second.length();
            if (n - m == 1) {
                //插入一个字符得到
                return oneInsert(first, second);
            } else if (m - n == 1) {
                //删除一个字符得到
                return oneInsert(second, first);
            } else if (m == n) {
                //符替换成不同的字符
                boolean foundDifference = false;
                for (int i = 0; i < m; i++) {
                    if (first.charAt(i) != second.charAt(i)) {
                        if (!foundDifference) {
                            foundDifference = true;
                        } else {
                            return false;
                        }
                    }
                }
                return true;
            } else {
                return false;
            }


        }

        /**
         * @param shorter
         * @param longer
         * @return
         */
        public boolean oneInsert(String shorter, String longer) {
            int length1 = shorter.length(), length2 = longer.length();
            int index1 = 0, index2 = 0;
            while (index1 < length1 && index2 < length2) {
                if (shorter.charAt(index1) == longer.charAt(index2)) {
                    index1++;
                }
                index2++;
                if (index2 - index1 > 1) {
                    return false;
                }
            }
            return true;
        }


    }
}
